const Common = require('../../utils/common.js');
import create from '../../utils/create2.js'
import store from '../../store/index.js'
import SessionUtil, {
  JxbHttpClient
} from "../../data/session/session"
import AppSceneUtil from '../../data/common/appScene.js'
import PagePromoterUtil, {
  PagePromoter
} from '../../data/common/pagePromoter.js';
import SystemUtil from '../../shell/system/system.js';
import InteractionUtil from '../../shell/ui/interaction.js';
import SessionSellingServerUtil from '../../data/session/sessionSellingServer.js'
import SellingServerUtil from '../../data/sellingServer.js'
import SessionUserUtil from '../../data/session/sessionUser.js'
import {
  RtLogUtil
} from '../../utils/log.js';
create(store, {
  data: {
    modalHidden: false,
    SearchKey: '',
    recommend: {},
    recommends: false,
    weekly: {},
    agent: {},
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 500,
    imageSize: [],
    current_consultant_info: {},
    theme: 1,
    search_module_style: true,
    phoneSrc: '../images/call.png',
    address: '',
    nearStore: {},
    storeList: [],
    showNear: false,
    unSelectList: [],
    windowHeight: 200,
    shop_message:'',
    is_use_customer_service:'',
    saleType:1,
  },
  onLoad: function () {
    // 开启转发按钮
    PagePromoterUtil.showShareMenu().then()
    InteractionUtil.showLoading(300)
    SessionUtil.getInstance().then(() => {
      // 注册当前页面的场景信息
      AppSceneUtil.setPageScene(this)
      wx.removeStorageSync('checkedlis');
      wx.removeStorageSync('tagValue');
      wx.removeStorageSync('specialString');
      // this.renderPage().then(() => {
      //   InteractionUtil.hideLoading(300)
      // }).catch((err) => {
      //   InteractionUtil.hideLoading()
      //   RtLogUtil.error(err)
      // })
      Common.w_widths(this);
      SessionUserUtil.renewCache().then(() => {
        let saleType = SessionUserUtil.getInstanceSync().salesModelType
        this.store.data.saleType = saleType
        this.setData({saleType})
        this.update()
      })
    })
    //获取系统,设备信息
    const systemInfo = SystemUtil.getSystemInfo(false)
    this.store.data.deviceInfo = systemInfo
    this.setData({
      windowHeight: systemInfo.windowHeight
    })
    this.update()
  },
  initNearStore: async function () {
    return await wx.$http().request('AppMaster/AgentUnion/getNearbyAgent').then(_ => {
      const { _data } = _
      const { data } = _data
      let { agentList, curAgent, shop_message} = data
      let unSelectList = []
      if (curAgent && curAgent.agent_id) {
        const index = agentList.findIndex(item => item.agent_id === curAgent.agent_id)
        if (index > -1) {
          if (!curAgent.is_serviceable) {
            const item = agentList.splice(index, 1)
            unSelectList.push(item[0])
          }
        } else {
          unSelectList.push(curAgent)
        }
      }
      return {
        list: agentList,
        current: curAgent,
        unSelectList,
        shop_message
      }
    })
  },
  initLocation() {
    wx.getSetting({
      success: res => {
        if (typeof (res.authSetting['scope.userLocation']) === "undefined") { // 从未触发过授权的情况
          wx.getLocation({ // 用户同意授权地理位置
            success: (res) => {
              this.getAddress(res)
            },
            fail: err => { // 用户拒绝授权地理位置
              this.getAddress(res)
            }
          })
        } else if (!res.authSetting['scope.userLocation']) {
          this.getAddress(res)
        } else if (res.authSetting['scope.userLocation']) {
          wx.getLocation({ // 用户同意授权地理位置
            success: (res) => {
              this.getAddress(res)
            }
          })
        }
      }
    })
  },
  getAddress(res) {
    const { latitude, longitude } = res
    // const longitude = 118.747307
    // const latitude = 32.0448
    wx.$http().request({ url: '/AppMaster/AgentUnion/getMyAddress', method: 'POST', data: { longitude, latitude, location_type: 'gps', is_select_address: 1 } }).then(res => {
      const { _data } = res
      this.initNearStore().then(r => {
        const { list, current, unSelectList, shop_message } = r
        wx.setStorage({
          key: 'position',
          data: { address: Object.assign({}, _data.data, { locationAddress: _data.data }), store: current },
        })
        this.setData({
          address: _data.data,
          unSelectList,
          storeList: list,
          nearStore: current,
          shop_message
        })
      })
      wx.$http().request({
        url: 'AppMaster/AgentUnion/selectAddress',
        data: Object.assign(_data.data, { location_type: 'gps' }),
        method: 'POST'
      }).then(_ => {
      })
    })
  },
  onShow: function () {
    getApp().getSaleMode().then(() => {
      this.renderPage().then(() => {
        InteractionUtil.hideLoading(300)
      }).catch((err) => {
        InteractionUtil.hideLoading()
        RtLogUtil.error(err)
      })
    })
    //获取定位
    wx.getStorage({
      key: 'position',
      success: (res) => {
        const { data } = res
        const { address } = data
        this.setData({
          address
        })
        this.initNearStore().then(r => {
          const { list, current, unSelectList, shop_message } = r
          this.setData({
            storeList: list,
            nearStore: current,
            unSelectList,
            shop_message
          })
        })
      },
      fail: err => {
        this.initLocation()
      }
    })
    wx.removeStorageSync('tagValue');
    wx.removeStorageSync('specialString');
    wx.removeStorageSync('checkedlis');
    SessionUtil.getInstance().then(session => {
      // 注册页面场景信息
      AppSceneUtil.setPageScene(this, false)
      let sellingServer = session.getTheSellingServerSync()
      wx.setNavigationBarTitle({
        title: sellingServer.showName
      })
      Common.showContips(this).then().catch(error => {
        throw error
      })
    }).catch(error => {
      wx.showToast({
        title: error.message,
        image: '/pages/images/fail.png',
        duration: 2000
      })
    })
  },
  onHide: function () {
    //当前顾问
    Common.show_bar(false, this);
  },

  findTrue: function (e) {
    wx.navigateTo({
      url: '/subPage/inspection/index',
    })
    // const{modalHidden} = this.data
    // this.setData({
    //   modalHidden: !modalHidden
    // })
  },

  //当前顾问详细信息
  show_bar: function (flag = true) {
    Common.show_bar(true, this);
  },
  // 计算图片高度
  imageLoad: function (e) {
    var index = e.currentTarget.dataset.id;;
    var page = this;
    var imageHeight = page.data.imageSize;
    imageHeight[index] = Common.imageLoadAn(e, page.data.w_width).toFixed(2);
    page.setData({
      imageSize: imageHeight
    })
  },
  //渲染页面
  renderPage: function () {
    return (new JxbHttpClient()).get('/AppMaster/Index/index').then(jxbResp => {
      if (jxbResp.data.search_module_style == 'sweepCode') {
        this.setData({
          search_module_style: false
        });
      } else {
        this.setData({
          search_module_style: true
        });
      }
      if(jxbResp){
        let iucs = jxbResp.data.agent.is_use_customer_service;
        if(iucs==1){
          this.setData({is_use_customer_service:true})
        }else{
          this.setData({is_use_customer_service:false})
        }
      }
        this.store.data.saleType = jxbResp.data.sale_type
        wx.setTabBarStyle({
          backgroundColor: jxbResp.data.sale_type * 1 === 2 ? '#650205' : jxbResp.data.sale_type * 1 === 1 ? '#000000' : '#2a396a'
        })
        wx.setNavigationBarColor({
          frontColor: '#ffffff', 
          backgroundColor: jxbResp.data.sale_type * 1 === 2 ? '#650205' : jxbResp.data.sale_type * 1 === 1 ? '#000000' : '#2a396a',
          animation: { 
              duration: 10,
              timingFunc: 'easeIn'
          }
        })
        /**是否开启商品列表页面,侧边栏分类*/
        this.store.data.sideBar = SessionSellingServerUtil.getInstanceSync().getTheAgentSync().isShowItemListMenu
        this.update()
      wx.setStorageSync('agent', jxbResp.data.agent);
      let renderProm
      // 如果index_type有值，就调模板接口
      switch (jxbResp.data.index_type) {
        case "page":
          this.setData({
            if_showIndex: true
          });
          var pageid = jxbResp.data.page_id;
          renderProm = this.showIndex(pageid);
          break;
        default:
          this.setData({
            activity_id: jxbResp.data.activity_id,
            Banner: jxbResp.data.list,
            if_showIndex: false
          });
          renderProm = Promise.all([
            this.LoadRecommend(),
            this.showWeekly(),
            this.seckill(),
            this.showBrand(4)
          ]);
      }
      return renderProm
    })
  },

  // 倒计时
  ShowCountDown: function (e) {
    var leftsecond = parseInt(e);
    //var day1=parseInt(leftsecond/(24*60*60*6)); 
    var day1 = Math.floor(leftsecond / (60 * 60 * 24));
    var hour = Math.floor((leftsecond) / 3600) + '';
    var hour1 = Math.floor((leftsecond - day1 * 24 * 60 * 60) / 3600);
    var minute = Math.floor((leftsecond - day1 * 24 * 60 * 60 - hour1 * 3600) / 60) + '';
    var second = Math.floor(leftsecond - day1 * 24 * 60 * 60 - hour1 * 3600 - minute * 60) + '';
    var divname = {};
    // divname.day = day1;
    divname.hour = hour.length < 2 ? ('0' + hour) : hour;
    divname.minute = minute.length < 2 ? ('0' + minute) : minute;
    divname.second = second.length < 2 ? ('0' + second) : second;
    return divname;
  },


  /**----------------------模块化接口-------------------- */
  showIndex: function (pageid) {
    return (new JxbHttpClient).get({
      url: 'AppMaster/PosSinglePage/indexPage',
      data: {
        page_id: pageid
      }
    }).then(jxbResp => {
      const indexList = jxbResp.data.positions;
      this.setData({
        indexList: indexList
      })
      // 把活动倒计时单独取出来
      for (var i = 0; i < indexList.length; i++) {
        if (indexList[i].module_type == "activity_list") {
          var a = indexList[i].module_data.activity_end_second;
          var b = setInterval(function () {
            a--
            if (a > 0) {
              this.setData({
                endDate: this.ShowCountDown(a),
              });
            } else {
              this.setData({
                endDates: 0,
              });
              clearTimeout(a);
            }
          }, 1000);
        }
      }
    })
  },

  /**----------------------非模块化接口-------------------- */
  // 品牌街
  showBrand: function (num) {
    return (new JxbHttpClient).get({
      url: 'AppMaster/BrandInfo/brandList',
      data: {
        number: num
      }
    }).then(jxbResp => {
      this.setData({
        brandlist: jxbResp.data
      })
    })
  },

  // 秒杀
  seckill: function () {
    return (new JxbHttpClient).get('/AppMaster/Index/activityThemeIndex').then(jxbResp => {
      var list = jxbResp.data;
      if (list) {
        var activity_info = list.activity_info;
        this.setData({
          seckills: list.list,
          activity_info: activity_info,
          activity_id: activity_info.activity_id
        });
        var a = activity_info.activity_end_second
        var b = setInterval(function () {
          a--
          if (a > 0) {
            this.setData({
              endDate: this.ShowCountDown(a),
            });
          } else {
            this.setData({
              endDates: 0,
            });
            clearTimeout(a);
          }
        }, 1000);
      }
    })
  },
  // 每周一香
  showWeekly: function () {
    return (new JxbHttpClient).get('/AppMaster/Index/itemThemeIndex').then(jxbResp => {
      var list = jxbResp.data;
      if (list) {
        this.setData({
          weekly: list.list,
          weeklyimg: list.item_theme_banner_uri,
          weeklytitle: list.tag_value
        });
      }
    })
  },

  // 推荐商品
  LoadRecommend: function () {
    return (new JxbHttpClient).get('/AppMaster/Index/newShowTagIndex').then(jxbResp => {
      if (jxbResp.data.length > 3) {
        this.setData({
          recommends: true,
        });
      }
      this.setData({
        recommend: jxbResp.data,
      });
    })
  },

  // 每周一香点击事件
  goList: function () {
    wx.setStorageSync('tagValue', "每周一香");
    wx.setStorageSync('if_refresh', 2);
    wx.switchTab({
      url: '/pages/product/index/index',
      success: function (e) {
        var page = getCurrentPages().pop();
        if (page == undefined || page == null) return;
        page.onLoad();
      }
    })
  },

  goList_module: function (e) {
    var tagValue = e.currentTarget.id;
    wx.setStorageSync('if_refresh', 2);
    wx.setStorageSync('tagValue', tagValue);
    wx.switchTab({
      url: '/pages/product/index/index',
      success: function (e) {
        var page = getCurrentPages().pop();
        if (page == undefined || page == null) return;
        page.onLoad();
      }
    })
  },

  goBrand: function () {
    wx.navigateTo({
      url: '/pages/index/brand/brand',
    })
  },

  showBrandList: function (e) {
    var page = this;
    var info = e.currentTarget.id.split("_");
    var id = info[0];
    wx.navigateTo({
      url: '/pages/product/brand/brand?brand_id=' + id,
    })
  },

  seckills: function () {
    wx.navigateTo({
      url: '/pages/activity/activity?activity_id=' + this.data.activity_id,
    })
  },

  // 模块化--活动页跳转
  seckills_module: function (e) {
    var id = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/activity/activity?activity_id=' + id,
    })
  },


  /**
   *  更新搜索关键词
   */
  updateSearchKey: function (e) {
    this.setData({
      SearchKey: e.detail.value
    })
  },
  //banner 详情页跳转
  goBannerLink: function (e) {
    var itemId = e.currentTarget.id;
    if (itemId) {
      wx.navigateTo({
        url: '/pages/product/detail/detail?itemId=' + itemId
      })
    }
  },

  // banner 列表跳转
  goListLink(e) {
    const {
      name
    } = e.currentTarget.dataset
    if (name) {
      wx.setStorageSync('if_refresh', 2);
      wx.navigateTo({
        url: '/pages/productList/index/index?tag=' + name
      })
    }
  },

  gospecialLink: function (e) {
    var name = e.target.dataset.name;
    if (name) {
      wx.setStorageSync('specialString', name);
      wx.setStorageSync('if_refresh', 2);
      wx.switchTab({
        url: '/pages/product/index/index'
      })
    }
  },

  // 跳到订单表单
  toDinner: function (e) {
    var id = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/index/foodform/index?id=' + id
    })
  },

  // banner 单页跳转
  goPageLink: function (e) {
    var pageid = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/index/single/single?tagId=' + pageid
    })
  },
  // 图文跳转开奖
  goprize: function (e) {
    var pageid = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/prize/index/index?id=' + pageid
    })
  },

  // 海量酒库跳转开奖
  gowine_cellar_list: function (e) {
    wx.navigateTo({
      url: '/pages/liquorstore/index/index'
    })
  },

  // banner 订餐跳转
  goDinnerLink: function (e) {
    var page = this;
    var title = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/index/food/index?title=' + title,
    })
  },

  /** 
   * 商品推荐--商品列表
   */
  goodsfilter: function (e) {
    var page = this;
    var tagValue = e.currentTarget.id;
    var data = e.currentTarget.id.split("_");
    var tagValue = data[0],
      tagType = data[1],
      tagId = data[2];
    if (tagType == '1') {
      wx.navigateTo({
        url: '/pages/index/single/single?tagId=' + tagId
      })
    } else if (tagType == '2') {
      wx.setStorageSync('tagValue', tagValue);
      wx.setStorageSync('if_refresh', 2);
      wx.switchTab({
        url: '/pages/product/index/index',
        success: function (e) {
          var page = getCurrentPages().pop();
          if (page == undefined || page == null) return;
          page.onLoad();
        }
      })
    }
  },
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  // 
  onShareAppMessage: function () {
    let session = SessionUtil.getInstanceSync(),
      resp = (new PagePromoter(this.route, {}))
        .setShareTitle(session.getTheSellingServerSync().showName)
        .buildShareInfo()
    console.log(resp, '分享内容')
    return resp
  },
  scan() {
    wx.navigateTo({
      url: '/pages/index/scanCode/index'
    })
  },
  onPageScroll(e) {
    if (e.scrollTop >= 370) {
      this.setData({
        theme: 2
      })
    } else {
      this.setData({
        theme: 1
      })
    }
  },
  goSearch() {
    wx.navigateTo({
      url: '../search/index',
    })
  },
  call(e) {
    const {
      phone
    } = e.currentTarget.dataset
    getApp().call(phone)
  },
  /**
   * 订餐(包间)
   */
  booking(e) {
    const {
      id
    } = e.currentTarget
    wx.navigateTo({
      url: `/pages/index/food/index?id=${id}`
    })
  },
  /**
   * 老酒频道
   */
  goWineOld(e) {
    const {
      dataset
    } = e.currentTarget
    const {
      year
    } = dataset
    wx.navigateTo({
      url: `/subPage/wineOld/index?year=${year}`
    })
  },
  changeAddress() {
    this.setData({
      showNear: true
    })
  },
  selectStore(e) {
    const { dataset } = e.currentTarget
    const { id } = dataset
    const { storeList, nearStore } = this.data
    const store = storeList.filter(item => item.agent_id === id)[0]
    if (nearStore.agent_id !== store.agent_id) {
      SessionSellingServerUtil.switchUnionStore(id).then(jxbResp=>{
        if(jxbResp._data){
          this.setData({
            showNear: false,
            nearStore: store
          })
        }
        let {address} = this.data
        wx.setStorage({
          key: 'position',
          data: { address, store }
        })
        this.renderPage()
        this.refreshPage()
      }).catch(err=>{
        InteractionUtil.showNotice(err.message)
      })
    } else {
      this.setData({
        showNear: false
      })
    }
  },
  modifyAddress() {
    wx.navigateTo({
      url: '/subPage/modifyAddress/index',
      success: () => {
        this.setData({
          showNear: false
        })
      }
    })
  },
  closeNear() {
    this.setData({
      showNear: false
    })
  },
  //切换店铺后,重置页面信息
  refreshPage() {
    wx.removeStorageSync('tagValue');
    wx.removeStorageSync('specialString');
    wx.removeStorageSync('checkedlis');
    SessionUtil.getInstance().then(session => {
      // 注册页面场景信息
      AppSceneUtil.setPageScene(this, false)
      let sellingServer = session.getTheSellingServerSync()
      console.log(sellingServer)
      wx.setNavigationBarTitle({
        title: sellingServer.showName
      })
      Common.showContips(this).then().catch(error => {
        throw error
      })
    }).catch(error => {
      wx.showToast({
        title: error.message,
        image: '/pages/images/fail.png',
        duration: 2000
      })
    })
  },
  preventD() {
    return
  },
  oneKey() {
    const { nearStore} = this.data
    const { agent_id} = nearStore
    wx.navigateTo({
      url: `/subPage/oneKey/index?id=${agent_id}`,
    })
  }
})